<template>
  <el-card>
    <!-- 顶部 -->
    <page-header>
      <template #left>
        <div class="container-left">
          <el-input v-model="title"
                    placeholder="根据用户名搜索"
                    style="margin-right: 10px" />
          <el-button size="small"
                     @click="perReset">清空</el-button>
          <el-button size="small"
                     type="primary"
                     style="background-color: #409eff; color:#fff"
                     @click="search">搜索</el-button>
        </div>
      </template>
      <template #right>
        <el-button type="success"
                   icon="el-icon-edit"
                   size="small"
                   style="background: #67c23a; color: #fff"
                   @click="handleOpenAdd">新增权限组</el-button>
      </template>
    </page-header>
    <!-- 文字提示 -->
    <el-alert :title="`${total}条消息`"
              type="info"
              show-icon
              :closable="false" />
    <el-table :data="permissionList">
      <el-table-column type="selection" />
      <el-table-column label="用户名"
                       prop="title" />
      <el-table-column label="日期"
                       prop="create_date" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary"
                     icon="el-icon-edit"
                     circle
                     @click="handleEditPer(row.id)" />
          <el-button type="danger"
                     icon="el-icon-delete"
                     circle
                     @click="handleDelPer(row.id)" />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination :current-page="query.page"
                   :page-sizes="[2, 3, 5, 10]"
                   :page-size="query.pagesize"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" />

    <!-- 新增权限 -->
    <el-dialog title="新增权限"
               :visible="addPermission"
               @close="handleAddClose">
      <el-form label-width="260px">
        <el-form-item label="用户名">
          <el-input v-model="formData.title"
                    placeholder="请输入用户名"
                    style="width: 50%" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-tree ref="tree"
                   :data="treeData"
                   show-checkbox
                   default-expand-all
                   node-key="id"
                   :props="{label: 'title'}" />
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <template #footer>
        <el-button @click="handleAddClose">取 消</el-button>
        <el-button type="primary"
                   style="background-color: #409eff; color:#fff"
                   @click="handleAddPer">确 定</el-button>
      </template>
    </el-dialog>
    <!-- 编辑权限 -->
    <el-dialog title="新增权限"
               :visible="EditPermission"
               @close="handleEditClose">
      <el-form label-width="260px">
        <el-form-item label="用户名">
          <el-input v-model="formData.title"
                    placeholder="请输入用户名"
                    style="width: 50%" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-tree ref="tree"
                   :data="treeData"
                   show-checkbox
                   default-expand-all
                   node-key="id"
                   :props="{label: 'title'}" />
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <template #footer>
        <el-button @click="handleEditClose">取 消</el-button>
        <el-button type="primary"
                   style="background-color: #409eff; color:#fff"
                   @click="handleEdit">确 定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import { getPermissionListAPI, addPermissionAPI, getPerDetailAPI, putPermissionAPI, delPermissionAPI } from '@/api/base-permission'
import { getMenusListAPI } from '@/api/base-menus'
import list2Tree from '@/utils/shift'
import dayjs from 'dayjs'
export default {
  name: 'PermissionsView',
  data () {
    return {
      // 权限组列表
      permissionList: [],
      query: {
        page: 1,
        pagesize: 10

      },
      // 控制新增显示
      addPermission: false,
      // 总条数
      total: 0,
      // 新增树形数据
      treeData: [],
      // 表单数据
      formData: {
        title: '',
        permissions: []
      },
      // 控制编辑弹窗
      EditPermission: false,
      // 搜索title
      title: ''
    }
  },
  created () {
    this.getPermissionList()
  },
  methods: {
    // 获取权限组名称
    async getPermissionList (title = '') {
      const res = await getPermissionListAPI({ ...this.query, title })
      this.permissionList = res.list
      console.log(res)
      this.total = res.counts
      // 转换日期格式
      res.list.forEach(item => {
        this.permissionList.forEach(obj => {
          obj.create_date = dayjs(item.create_date).format('YYYY-MM-DD')
        })
      })
      const resp = await getMenusListAPI()
      // console.log(res)
      // 树转列
      const arr = this.handle(resp)
      // 添加一个父级
      arr.push({
        title: '系统菜单和权限点',
        pid: 0,
        id: null
      })
      //  列转树
      this.treeData = list2Tree(arr, 0)
    },
    // 关闭新增
    handleAddClose () {
      this.addPermission = false
    },
    // 打开新增
    async handleOpenAdd () {
      this.addPermission = true
    },
    // 处理树转列表数据函数
    handle (tree) {
      const arr = []
      tree.forEach(item => {
        // 判断有无孩子
        if (item.points) {
          const children = this.handle(item.points)
          delete item.points
          arr.push(item, ...children)
        } else if (item.childs) {
          const children = this.handle(item.childs)
          delete item.childs
          arr.push(item, ...children)
        } else {
          arr.push(item)
        }
      })
      return arr
    },
    // 新增权限组
    async handleAddPer () {
      this.formData.permissions = this.$refs.tree.getCheckedKeys()
      if (this.formData.permissions.includes(null)) {
        const index = this.formData.permissions.findIndex(item => item === null)
        this.formData.permissions.splice(index, 1)
      }
      await addPermissionAPI(this.formData)
      // console.log(res)
      // 关闭弹窗
      this.handleAddClose()
      // 刷新列表
      this.getPermissionList()
    },
    // 关闭编辑弹窗
    handleEditClose () {
      this.EditPermission = false
      // this.$refs.tree.setCheckedKeys([])
    },
    // 打开编辑弹窗（有bug）
    async handleEditPer (id) {
      this.EditId = id
      this.EditPermission = true

      try {
        // 回显请求
        const res = await getPerDetailAPI(id)
        this.formData = res
        const arr = res.permissions
        if (this.formData.permissions.length) {
          this.$refs.tree.setCheckedKeys(arr)
        } else {
          this.$message.error('失败')
        }
      } catch (e) {
        //
      }
    },
    // 编辑权限
    async handleEdit () {
      this.formData.permissions = this.$refs.tree.getCheckedKeys()
      if (this.formData.permissions.includes(null)) {
        const index = this.formData.permissions.findIndex(item => item === null)
        this.formData.permissions.splice(index, 1)
      }
      await putPermissionAPI({
        id: this.EditId,
        ...this.formData
      })
      this.handleEditClose()
      this.getPermissionList()
    },
    // 删除权限
    async handleDelPer (id) {
      try {
        await this.$confirm('确定删除', '提示', {
          type: 'warning'
        })
        await delPermissionAPI(id)
        // console.log(res)
        this.getPermissionList()
        this.$message.success('删除成功')
      } catch (e) {
        //
      }
    },

    // 页面条数发生变化时
    handleSizeChange (val) {
      this.query.pagesize = val
      this.getPermissionList()
    },
    // 页码发生变化时
    handleCurrentChange (val) {
      this.query.page = val
      this.getPermissionList()
    },
    // 搜索
    search () {
      this.getPermissionList(this.title)
    },
    // 清空
    perReset () {
      this.getPermissionList()
      this.title = ''
    }

  }
}
</script>

<style scoped lang="scss">
/* .el-card {
  margin: 20px;
  margin-top: 90px;
} */
.container-left {
  display: flex;
}
.el-alert {
  margin-top: 20px;
}
.el-button--primary {
  color: #409eff;
  background-color: #ecf5ff;
  &:hover {
    color: #fff;
    background-color: #409eff;
  }
}
.el-button--danger {
  color: #f56c6c;
  background-color: #fef0f0;
  &:hover {
    color: #fef0f0;
    background-color: #f56c6c;
  }
}
</style>
